'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import useSWRInfinite from 'swr/infinite'
import zhCN from 'antd/es/locale/zh_CN'
import useSWR from 'swr'
import { useTranslation } from 'react-i18next'
import { useDebounceFn } from 'ahooks'
import {
  RiHome3Line,
  RiMessage3Line,
  RiRobot2Line,
  RiRobot3Line,
  RiToolsLine,
} from '@remixicon/react'
import { Button as AntButton, Layout, Menu, ConfigProvider } from 'antd'
import {
  ApartmentOutlined,
  PlusOutlined,
  TeamOutlined,
  UsbOutlined,
  UserOutlined,
} from '@ant-design/icons'
import useAppsQueryState from './hooks/useAppsQueryState'
import AllPage from './component/allPage'
import AreaPage from './component/areaPage'
import AreaEdit from './component/areaPage/areaEdit'
import WorkflowPage from './component/workflowPage'
import MetabolicPage from './component/metabolicPage'
import DcoosPage from './component/dcoosPage'
import ReleaseManager from './component/releaseManagement'
import WorkSpaceSecondPage from './component/workSpaceSecondPage'
import ChatPage from './component/chatPage'
import AgentChatPage from './component/agentChatPage'
import ApplicationAuthority from './component/applicationAuthority'
import EditAuthority from './component/editAuthority'
import ManagerPage from './component/managerPage'
import ApplicationExamine from './component/applicationExamine'
import InformationManagement from './component/informationManagement/informationManagement'
import type { OpenTypes } from './component/base/createModal'
import CreateModal from './component/base/createModal'
import DcoosSignPage from './component/dcoosSignPage'
import styles from './Apps.module.scss'
import type { AppListResponse } from '@/models/app'
import { fetchAppList } from '@/service/apps'
import { fetchDcoosList, fetchInstallPlugin, fetchPluginProviders, meunClickLog } from '@/service/common'
import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
import Button from '@/app/components/base/button'
import TopHeader from '@/layout/Header'
import { useAppContext } from '@/context/app-context'
import ProjectSpace from '@/app/(commonLayout)/apps/component/ProjectSpace'
import ProjectMember from '@/app/(commonLayout)/apps/component/ProjectSpace/member'
import { getQueryParams } from '@/utils/getUrlParams'
import GlobalUrl from '@/GlobalUrl'
import DisableDevtool from 'disable-devtool';
import MpcManage from './component/mpcManage'
const { Content, Sider } = Layout

const Apps = () => {
  const { userProfile }: any = useAppContext()
  const { t } = useTranslation()
  const category = getQueryParams('category')
  const tenantId = getQueryParams('tenant_id')
  const [activeTab, setActiveTab] = useTabSearchParams({
    defaultTab: 'all',
  })
  const [isUrlReady, setIsUrlReady] = useState(false); // 用于判断URL和参数是否准备好
  const [activeId, setActiveId] = useState('')
  const [activeArea, setActiveArea] = useState<string>('')
  const getKey = (
    pageIndex: number,
    previousPageData: AppListResponse,
    activeTab: string,
    tags: string[],
    activeId: any
  ) => {
    if (!pageIndex || previousPageData.has_more) {
      const params: any = {
        url: '/apps',
        params: {
          page: pageIndex + 1,
          limit: 100,
        },
      };

      if (category === 'workSpaceSecondPage') {
        params.params.tenant_id = activeId.id || tenantId;
      }

      if (activeTab !== 'area' && activeTab !== 'chat') {
        params.params.mode = activeTab;
        if (activeTab === 'agent-chat' || activeTab === 'metabolic' || activeTab === 'workflow') {
          params.params.tenant_id = '9a0ead78-3689-4bf0-8000-9ab72250cfb2';
          params.url = '/global-apps';
        }
      } else {
        delete params.params.mode;
        if (activeArea) params.params.tenant_id = activeArea;
      }

      if (tags.length) params.params.tag_ids = tags;

      return params;
    }
    return null;
  };

  const { query: { tagIDs = [], keywords = '' }, setQuery } = useAppsQueryState()
  const [isAddOpen, setIsAddOpen] = useState<OpenTypes>({
    isOpen: false,
    title: '',
  })
  const [tagFilterValue, setTagFilterValue] = useState<string[]>(tagIDs)
  const [searchKeywords, setSearchKeywords] = useState(keywords)
  const setKeywords = useCallback((keywords: string) => {
    setQuery(prev => ({ ...prev, keywords }))
  }, [setQuery])
  const setTagIDs = useCallback((tagIDs: string[]) => {
    setQuery(prev => ({ ...prev, tagIDs }))
  }, [setQuery])

  const { data: dcoosList, mutate: dcoosListMutate } = useSWR(GlobalUrl.wangyun_defaultUrlIp_agent_platform + `/interface/api/api-info?page_index=1&page_size=999&create_by=${userProfile?.employee_number}`, fetchDcoosList)
  const { data: plugins, mutate: pluginsMutate } = useSWR(
    activeArea ? `/workspaces/current/tool-providers?tenant_id=${activeArea}` : null,
    fetchPluginProviders
  );
  const { data: customPlugins, mutate: customPluginsMutate } = useSWR(GlobalUrl.wangyun_NEXT_PUBLIC_API_PREFIX + '/workspaces/current/tools/api/flat', fetchInstallPlugin)
  const { data: builtinPlugins, mutate: builtinPluginsMutate } = useSWR(GlobalUrl.wangyun_NEXT_PUBLIC_API_PREFIX + '/workspaces/current/tools/builtin/flat', fetchInstallPlugin)
  const { data, isLoading, setSize, mutate } = useSWRInfinite(
    (pageIndex: number, previousPageData: AppListResponse) => {
      if (!isUrlReady) return null; // 当 isUrlReady 为 false 时，返回 null
      return getKey(pageIndex, previousPageData, activeTab, tagIDs, activeId);
    },
    fetchAppList,
    { revalidateFirstPage: true }
  );

  // 其他代码保持不变

  const anchorRef = useRef<HTMLDivElement>(null)
  const options: any = [
    { value: 'all', key: 'all', label: '首页', text: t('app.types.area'), icon: <RiHome3Line className='w-[14px] h-[14px] mr-1' /> },
    { value: 'area', key: 'area', label: '个人空间', text: t('app.types.area'), icon: <UserOutlined className='w-[14px] h-[14px] mr-1' /> },
    { value: 'projectSpace', key: 'projectSpace', label: '项目空间', text: t('app.types.projectSpace'), icon: <TeamOutlined className='w-[14px] h-[14px] mr-1' /> },
    { value: 'tansou', key: 'tansou', type: 'group', label: (<div className={styles.tansuo}> 探索</div >) },
    { value: 'mcpManage', key: 'mcpManage', label: 'MCP管理', text: t('app.types.workflow'), icon: <UsbOutlined className='w-[14px] h-[14px] mr-1' /> },
    { value: 'agent-chat', key: 'agent-chat', label: 'Agent广场', text: t('app.types.agent'), icon: <RiRobot3Line className='w-[14px] h-[14px] mr-1' /> },
    { value: 'chat', key: 'chat', label: '插件广场', text: t('app.types.chatbot'), icon: <RiMessage3Line className='w-[14px] h-[14px] mr-1' /> },
    { value: 'workflow', key: 'workflow', label: '工作流', text: t('app.types.workflow'), icon: <ApartmentOutlined className='w-[14px] h-[14px] mr-1' /> },
    { value: 'metabolic', key: 'metabolic', label: '多智能体', text: t('app.types.workflow'), icon: <RiRobot2Line className='w-[14px] h-[14px] mr-1' /> },
    { value: 'informationManagement', key: 'informationManagement', label: 'API信息管理', text: t('app.types.informationManagement'), icon: <RiRobot2Line className='w-[14px] h-[14px] mr-1' /> },
    { value: 'dcoos', key: 'dcoos', label: 'api注册', text: 'api注册', icon: <RiToolsLine className='w-[14px] h-[14px] mr-1' /> },
  ]
  // Project Space
  useEffect(() => {
    document.title = `${t('common.menus.apps')}`
    if (localStorage.getItem(NEED_REFRESH_APP_LIST_KEY) === '1') {
      localStorage.removeItem(NEED_REFRESH_APP_LIST_KEY)
      mutate()
    }
    //开启开发者模式的方法
    // DisableDevtool();
  }, [])

  const hasMore = data?.at(-1)?.has_more ?? true
  useEffect(() => {
    let observer: IntersectionObserver | undefined
    if (anchorRef.current) {
      observer = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && !isLoading && hasMore)
          setSize((size: number) => size + 1)
      }, { rootMargin: '100px' })
      observer.observe(anchorRef.current)
    }
    return () => observer?.disconnect()
  }, [isLoading, setSize, anchorRef, mutate, hasMore])

  useEffect(() => {
    // 检查URL及参数是否准备好
    if (category) {
      setIsUrlReady(true); // 设置为true，表示可以开始请求
    }
  }, [category]); // 依赖这些参数，当它们改变时检查是否准备好

  const { run: handleSearch } = useDebounceFn(() => {
    setSearchKeywords(keywords)
  }, { wait: 500 })
  const handleKeywordsChange = (value: string) => {
    setKeywords(value)
    handleSearch()
  }

  const { run: handleTagsUpdate } = useDebounceFn(() => {
    setTagIDs(tagFilterValue)
  }, { wait: 500 })
  const handleTagsChange = (value: string[]) => {
    setTagFilterValue(value)
    handleTagsUpdate()
  }

  // content展示
  const showComponents = (tab: string) => {
    switch (tab) {
      case 'all':
        return <AllPage data={data} />
      case 'area':
        return <AreaPage data={data?.[0]} plugins={plugins ?? []} mutate={mutate} pluginsMutate={pluginsMutate} setActiveTab={setActiveTab} setCallback={setActiveArea} />
      case 'workflow':
        return <WorkflowPage data={data?.[0]} mutate={mutate} setCallback={setActiveArea} />
      case 'agent-chat':
        return <AgentChatPage data={data?.[0]} mutate={mutate} setCallback={setActiveArea} />
      case 'projectSpace':
        return <ProjectSpace data={data?.[0]} mutate={mutate} setCallback={setActiveArea} setActiveTab={setActiveTab} setActiveId={setActiveId} />
      case 'chat':
        return <ChatPage data={builtinPlugins ?? []} mutate={customPluginsMutate} setCallback={setActiveArea} />
      case 'detail':
        return <AreaEdit setActiveTab={setActiveTab} setCallback={setActiveArea} />
      case 'metabolic':
        return <MetabolicPage data={data?.[0]} mutate={mutate} setCallback={setActiveArea} />
      case 'mcpManage':
        return <MpcManage />
      case 'dcoos':
        return <DcoosPage data={dcoosList} mutate={dcoosListMutate} setActiveTab={setActiveTab} />
      case 'dcoos-sign':
        return <DcoosSignPage data={dcoosList?.[0]} mutate={dcoosListMutate} setActiveTab={setActiveTab} />
      case 'release':
        return <ReleaseManager data={data?.[0]} mutate={mutate} setActiveTab={setActiveTab} />
      case 'workSpaceSecondPage':
        return <WorkSpaceSecondPage data={data?.[0]} plugins={plugins ?? []} setActiveTab={setActiveTab} mutate={mutate} setCallback={setActiveArea} pluginsMutate={pluginsMutate} />
      case 'super-manager':
        return <ManagerPage />
      case 'project-member':
        return <ProjectMember setActiveTab={setActiveTab} setCallback={setActiveArea} />
      case 'applicationAuthority': // 应用权限
        return <ApplicationAuthority setActiveTab={setActiveTab} />
      case 'editAuthority': // 编辑权限
        return <EditAuthority setActiveTab={setActiveTab} />
      case 'appExamine': // 应用审批
        return <ApplicationExamine setActiveTab={setActiveTab} />
      case 'informationManagement': //API信息管理
        return <InformationManagement data={data?.[0]} mutate={mutate} setCallback={setActiveArea} />
    }
  }
  const setCurrentMenu = (item: any) => {
    const menuName = options.find((i: any) => i.key === item.keyPath[0])?.label
    if (item.keyPath[0] === 'tansou')
      return false

    setActiveTab(item.keyPath[0])
    meunClickLog({
      body: {
        menuName,
        menuUrl: location.href,
        source: 'agentplatform',
        employeeNumber: userProfile?.employee_number,
      },
    })
  }

  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.leftContainer}>
        {/* <div className='sticky top-0 flex justify-between items-center pt-4 px-12 pb-2 leading-[56px] bg-gray-100 z-10 flex-wrap gap-y-2'>
        <TabSliderNew
          value={activeTab}
          onChange={setActiveTab}
          options={options}
        />
        <div className='flex items-center gap-2'>
          <TagFilter type='app' value={tagFilterValue} onChange={handleTagsChange} />
          <SearchInput className='w-[200px]' value={keywords} onChange={handleKeywordsChange} />
        </div>
      </div>
      <nav className='grid content-start grid-cols-1 gap-4 px-12 pt-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 grow shrink-0'>
        {isCurrentWorkspaceEditor
          && <NewAppCard onSuccess={mutate} />}
        {data?.map(({ data: apps }: any) => apps.map((app: any) => (
          <AppCard key={app.id} app={app} onRefresh={mutate} />
        )))}
        <CheckModal />
      </nav>
      <div ref={anchorRef} className='h-0'> </div>
      {showTagManagementModal && (
        <TagManagementModal type='app' show={showTagManagementModal} />
      )} */}
        <Layout>
          <TopHeader />
          <Layout>
            <Sider width={200} className="flex flex-col" style={{ background: '#fff', height: '100%' }}>
              <div className="my-[14px] px-[9px]">
                <Button className="btn-primary" style={{ width: '100%', height: '40px' }} onClick={() => setIsAddOpen({
                  isOpen: true,
                  title: '立即创建',
                })}>
                  <PlusOutlined className="pr-[10px]" />立即创建
                </Button>
              </div>
              <Menu
                className='my-[14px]'
                mode="inline"
                selectedKeys={[activeTab]}
                onClick={item => setCurrentMenu(item)}
                defaultSelectedKeys={['all']}
                style={{ borderRight: 0 }}
                items={options}
              />
              <section style={{ display: userProfile.is_super_admin ? '' : 'none' }} className="p-4 border-solid border-[#f2f2f2] border-t-[1px] flex">
                <AntButton
                  style={{ backgroundColor: '#e8f0ff' }}
                  className="text-[#387dff] border-none" size="large" block
                  onClick={() => setActiveTab('super-manager')}
                >
                  超级管理员
                </AntButton>
              </section>
            </Sider>
            <Layout style={{ overflow: 'hidden' }} className='miantainer'>
              <Content style={{ padding: '0 28px 24px 28px', height: 'calc(100% - 60px)', overflowX: 'auto' }}>
                {showComponents(activeTab)}
              </Content>
            </Layout>
          </Layout>
        </Layout>
        {isAddOpen.isOpen ? <CreateModal isAddOpen={isAddOpen} onClose={(val: boolean) => setIsAddOpen({ ...isAddOpen, isOpen: val })} /> : null}
      </div>
    </ConfigProvider>
  )
}

export default Apps
